// --------------------------------------------------------------------------------------------------------------------
// <copyright file="KukaLBR4Controller.cs" company="Microsoft Corporation">
// The MIT License (MIT)
// 
// Copyright (c) 2014, Microsoft Corporation
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy
//  of this software and associated documentation files (the "Software"), to deal
//  in the Software without restriction, including without limitation the rights
//  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//  copies of the Software, and to permit persons to whom the Software is
//  furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in
//  all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//  THE SOFTWARE.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------

namespace Microsoft.Robotics.Hardware.KukaLBR
{
    using System;

    using Microsoft.Robotics.Manipulation;
    using Microsoft.Robotics.Manipulation.ControllerStateMachine;
    using Microsoft.Robotics.Numerics;

    /// <summary>
    /// Base class for controllers for the KUKA LBR4
    /// </summary>
    public abstract class KukaLBR4Controller 
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="KukaLBR4Controller"/> class.
        /// </summary>
        /// <param name="registerManager">Register manager for working registers.</param>
        public KukaLBR4Controller(KukaLBR4WorkingRegisterManager registerManager)
        {
            this.RegisterManager = registerManager;
            this.WorkingRegisterArray = new KukaLBR4WorkingRegisterArray();
        }

        /// <summary>
        /// Gets or sets working registers stored as an array of arrays
        /// </summary>
        protected KukaLBR4WorkingRegisterArray WorkingRegisterArray { get; set; }

        /// <summary>
        /// Gets an object that handles assignment of registers
        /// </summary>
        protected KukaLBR4WorkingRegisterManager RegisterManager { get; private set; }

        /// <summary>
        /// Builds a state machine controller
        /// </summary>
        /// <returns>A state machine based controller</returns>
        public virtual ControllerStateMachineDescription BuildStateMachineDescription()
        {
            return this.BuildControllerStateMachine().ToControllerStateMachineDescription();
        }

        /// <summary>
        /// Builds a ManipulatorStatus message from a feedback message from the KUKA LBR4 controller.
        /// </summary>
        /// <param name="message">A feedback message from a KUKA LBR4 controller </param>
        /// <returns> Manipulation status. </returns>
        public virtual ManipulatorStatus GetManipulatorStatus(FeedbackMessageManaged message)
        {
            KukaLBR4InferredState inferredState = this.GetInferredState(message);

            double[] jointCommandedPositions = new double[KukaLBR4PlusCsharpDefinitionsNativeMethods.NUM_JOINTS];

            // Get the current command by adding the commanded joint position (CommandedJointPositionRegister) and
            // the commanded joint offset (CommandedJointOffsetRegister)
            // refer to page 33 in http://sharepoint/sites/Baker/SiteAssets/Baker%20Wiki/LBR4+%20Manuals/KUKA_FRI_10_en.pdf
            // for the math behind
            for (int i = 0; i < jointCommandedPositions.Length; ++i)
            {
                jointCommandedPositions[i] = message.ReportedCommandedJointOffsetRegister[i] + message.ReportedCommandedJointPositionRegister[i];
            }
            
            return new ManipulatorStatus(
               message.TimestampInMsRegister,
               new Pose(HomogenousTransform.FromFrameArray(message.MeasuredCartesianPositionRegister)),
               new Pose(HomogenousTransform.FromFrameArray(message.ReportedCommandedCartesianPositionRegister)),
               message.MeasuredJointPositionRegister,
               message.MeasuredJointVelocityRegister,
               jointCommandedPositions,
               message.MeasuredJointTorqueRegister,
               message.MeasuredExternalJointTorqueRegister,
               message.EstimatedTCPForceTorqueRegister,
               inferredState.TcpUnexpectedForceOccured);
        }

        /// <summary>
        /// Gets a copy of the initial working register configuration
        /// </summary>
        /// <returns>A set of working registers.</returns>
        public virtual WorkingRegisterMessageManaged GetCopyOfInitialWorkingRegisterConfiguration()
        {
            WorkingRegisterMessageManaged workingRegisterMessageManaged = new WorkingRegisterMessageManaged();
            workingRegisterMessageManaged.CopyFromArrayOfArrays(this.WorkingRegisterArray.Registers);
            return workingRegisterMessageManaged;
        }

        /// <summary>
        /// Default method for getting inferred state.
        /// </summary>
        /// <param name="message"> A feedback message from a KUKA LBR4 controller. </param>
        /// <returns> Inferred state. </returns>
        protected virtual KukaLBR4InferredState GetInferredState(FeedbackMessageManaged message)
        {
            return new KukaLBR4InferredState();
        }

        /// <summary>
        /// Builds the controller state machine utilized by the controller
        /// </summary>
        /// <returns>A controller state machine.</returns>
        protected abstract ControllerStateMachine BuildControllerStateMachine();
    }
}
